package gold.digger;

import javafx.util.Pair;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC331 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public boolean isValidSerialization(String preorder) {
            String[] preorderStrArray = preorder.split(",");
            Stack<Pair<Integer, Integer>> stack = new Stack<>();
            if (preorderStrArray[0].equals("#")) return preorderStrArray.length <= 1;
            else stack.push(new Pair<>(Integer.parseInt(preorderStrArray[0]), 1));

            for (int i = 1; i < preorderStrArray.length; i++) {
                if (stack.isEmpty()) return false;
                if (preorderStrArray[i].equals("#")) {
                    Pair<Integer, Integer> last = stack.pop();
                    if (last.getValue() == 1) stack.push(new Pair<>(last.getKey(), 0));
                    else {
                        while (!stack.isEmpty() && stack.peek().getValue() == 0) stack.pop();
                        if (!stack.isEmpty()) {
                            stack.push(new Pair<>(stack.pop().getKey(), 0));
                        }
                    }
                } else {
                    int num = Integer.parseInt(preorderStrArray[i]);
                    stack.push(new Pair<>(num, 1));
                }
            }

            return stack.isEmpty();
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"));
//        System.out.println(solution.isValidSerialization("1,#"));
    }

    public static void main(String[] args) throws Exception {
        LC331 an = new LC331();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
